package com.example.generator.service;

import com.example.generator.model.ColumnInfo;
import com.example.generator.model.TableInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DatabaseService {
    private static final Logger log = LoggerFactory.getLogger(DatabaseService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取表信息
     */
    public TableInfo getTableInfo(String tableName) {
        TableInfo tableInfo = new TableInfo();
        tableInfo.setTableName(tableName);
        tableInfo.setClassName(convertToCamelCase(tableName, true));
        
        // 获取表注释
        String tableComment = getTableComment(tableName);
        tableInfo.setComment(tableComment);
        
        // 获取列信息
        List<ColumnInfo> columns = getColumnInfo(tableName);
        tableInfo.setColumns(columns);
        
        return tableInfo;
    }

    /**
     * 获取表注释
     */
    private String getTableComment(String tableName) {
        String sql = "SELECT table_comment FROM information_schema.tables " +
                    "WHERE table_schema = database() AND table_name = ?";
        return jdbcTemplate.queryForObject(sql, String.class, tableName);
    }

    /**
     * 获取列信息
     */
    private List<ColumnInfo> getColumnInfo(String tableName) {
        String sql = "SELECT column_name, data_type, column_comment, is_nullable, " +
                    "column_key FROM information_schema.columns " +
                    "WHERE table_schema = database() AND table_name = ? " +
                    "ORDER BY ordinal_position";
        
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            ColumnInfo columnInfo = new ColumnInfo();
            String columnName = rs.getString("column_name");
            columnInfo.setColumnName(columnName);
            String propertyName = convertToCamelCase(columnName, false);
            if ("tinyint".equalsIgnoreCase(rs.getString("data_type")) && 
                (propertyName.startsWith("is") || propertyName.startsWith("has"))) {
                propertyName = propertyName.substring(2);
                propertyName = Character.toLowerCase(propertyName.charAt(0)) + propertyName.substring(1);
            }
            columnInfo.setPropertyName(propertyName);
            columnInfo.setDataType(rs.getString("data_type"));
            columnInfo.setJavaType(getJavaType(rs.getString("data_type")));
            columnInfo.setComment(rs.getString("column_comment"));
            columnInfo.setNullable("YES".equals(rs.getString("is_nullable")));
            columnInfo.setPrimaryKey("PRI".equals(rs.getString("column_key")));
            return columnInfo;
        }, tableName);
    }

    /**
     * 下划线转驼峰命名
     */
    private String convertToCamelCase(String name, boolean firstUpper) {
        StringBuilder result = new StringBuilder();
        boolean nextUpper = firstUpper;
        
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (c == '_') {
                nextUpper = true;
            } else {
                result.append(nextUpper ? Character.toUpperCase(c) : Character.toLowerCase(c));
                nextUpper = false;
            }
        }
        
        return result.toString();
    }

    /**
     * 获取Java类型
     */
    private String getJavaType(String dataType) {
        switch (dataType.toLowerCase()) {
            case "varchar":
            case "char":
            case "text":
                return "String";
            case "int":
            case "tinyint":
                return "Integer";
            case "bigint":
                return "Long";
            case "decimal":
                return "BigDecimal";
            case "datetime":
            case "timestamp":
                return "Date";
            default:
                return "String";
        }
    }

    /**
     * 获取所有表信息
     */
    public List<Map<String, Object>> getAllTables() {
        String sql = "SELECT table_name as tableName, table_comment as tableComment " +
                    "FROM information_schema.tables " +
                    "WHERE table_schema = database() " +
                    "ORDER BY table_name";
        
        return jdbcTemplate.queryForList(sql);
    }
} 